<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="应用名称" prop="appName">
        <el-input
          v-model="queryParams.appName"
          placeholder="请输入消息标题"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="起止时间" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:notice:add']"
          >上传</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="noticeList">
      <el-table-column label="序号" align="center" prop="id" width="100" />
      <el-table-column
        label="应用名"
        align="center"
        prop="appName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="上架时间"
        align="center"
        prop="issuedDate"
        width="180"
      />
      <el-table-column label="状态" align="center" width="100"
        ><template #default="scope">
          {{ ["未上架", "已上架"][scope.row.issuedFlag] }}</template
        >
      </el-table-column>

      <el-table-column
        label="强制更新"
        align="center"
        prop="forceUpdate"
        width="100"
      >
        <template #default="scope">
          <el-switch
            :before-change="beforeUpdate"
            @change="handleUpdate(scope.row)"
            v-model="scope.row.forceUpdate"
            :disabled="scope.row.forceUpdate == 1"
            active-value="1"
            inactive-value="0"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="版本号"
        align="center"
        prop="versionNum"
        width="100"
      />
      <el-table-column
        width="140"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="上架" placement="top">
            <el-button
              :disabled="scope.row.issuedFlag == 1"
              link
              type="primary"
              icon="upload"
              @click="handlePublish(scope.row)"
              v-hasPermi="['system:notice:edit']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              :disabled="scope.row.issuedFlag == 1"
              link
              type="primary"
              icon="delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:notice:edit']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageSize"
      v-model:limit="queryParams.pageCount"
      @pagination="getList"
    />

    <!-- 添加 -->
    <el-dialog :title="title" v-model="open" width="560px" append-to-body>
      <el-form
        ref="systemMessageRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-row>
          <el-col :span="24">
            <el-col :span="24">
              <el-form-item label="应用名称" prop="appName">
                <el-input
                  v-model="form.appName"
                  maxlength="10"
                  show-word-limit
                  placeholder="请输入应用名称"
                />
              </el-form-item>
              <el-form-item label="版本号" prop="versionNum">
                <el-input
                  v-model="form.versionNum"
                  maxlength="10"
                  show-word-limit
                  placeholder="请输入版本号"
                />
              </el-form-item>
            </el-col>
            <el-form-item label="APK文件" prop="appPath">
              <FileUpload
                v-model="form.appPath"
                ref="fileUploadRefs"
                :limit="1"
                :file-size="80"
                :file-type="['apk']"
              ></FileUpload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SystemMessage">
import { list, add, detail, del, edit } from "@/api/device/app";

const { proxy } = getCurrentInstance();
const noticeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");
const detailVisible = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageCount: 10,
    pageSize: 1,
    appName: "",
    dateRange: "",
  },
  rules: {
    appName: [{ required: true, message: "应用名称不能为空", trigger: "blur" }],
    versionNum: [
      { required: true, message: "版本号不能为空", trigger: "blur" },
    ],
    appPath: [{ required: true, message: "APK文件必须上传", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询消息列表 */
function getList() {
  loading.value = true;
  list({
    ...queryParams.value,
    startTime:
      queryParams.value.dateRange.length > 0
        ? queryParams.value.dateRange[0]
        : "",
    endTime:
      queryParams.value.dateRange.length > 0
        ? queryParams.value.dateRange[1]
        : "",
  }).then((response) => {
    noticeList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  proxy.resetForm("systemMessageRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageSize = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "发布消息";
}
/**上架 */
function handlePublish(row) {
  const id = row.id;
  proxy.$modal
    .confirm(
      `该应用【${
        row.forceUpdate == 0 ? "未" : "已"
      }开启强更】，确定上架该应用？`
    )
    .then(function () {
      edit({
        id,
        issuedFlag: 1,
      }).then((response) => {
        getList();
        detailVisible.value = true;
      });
    });
}
function beforeUpdate() {
  return proxy.$modal
    .confirm("确定要强制更新该应用吗？")
    .then(() => {
      return new Promise((resolve, reject) => {
        return resolve(true);
      });
    })
    .catch(() => {
      return new Promise((resolve, reject) => {
        return reject(false);
      });
    });
}
/**强制更新 */
function handleUpdate(row) {
  console.log(row);
  const id = row.id;
  edit({
    id,
    forceUpdate: 1,
  }).then((response) => {
    getList();
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["systemMessageRef"].validate((valid) => {
    if (valid) {
      add(form.value).then((response) => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      });
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id;
  proxy.$modal
    .confirm("确定要删除该应用吗？")
    .then(function () {
      return del(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

getList();
</script>

<style scoped lang="scss">
.batchDel {
  margin-top: 24px;
}
</style>
